package com.example.nonacademic_education.service.impl;

import com.example.nonacademic_education.dao.AdminDao;
import com.example.nonacademic_education.dao.MsgDao;
import com.example.nonacademic_education.dao.StudentDao;
import com.example.nonacademic_education.data.response.MsgRes;
import com.example.nonacademic_education.entity.Department;
import com.example.nonacademic_education.entity.Msg;
import com.example.nonacademic_education.service.MsgService;
import com.example.nonacademic_education.util.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MsgServiceImpl implements MsgService {
    @Resource
    private MsgDao msgDao;
    @Resource
    private AdminDao adminDao;
    @Resource
    private StudentDao studentDao;

    @Override
    public R historyMsg(Long recipientId, Integer page, Integer size, String content, Integer isRead) {
        if (page < 1) {
            return R.error("页数不能小于1");
        }
        page = (page - 1) * size;
        List<MsgRes> list = msgDao.getList(page, size, recipientId, content, isRead);
        Integer total = msgDao.getNumber(recipientId, content, isRead);
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        data.put("total", total);
        return R.ok(data, "success");
    }

    @Override
    public R sendMsg(Msg msg) {
        msg.setIsRead(0);
        msg.setSendTime(new Date(System.currentTimeMillis()));
        if (msgDao.addOne(msg) == 1) {
            return R.ok("send message successfully");
        } else {
            return R.error("发送消息出现错误，请稍后再试，或联系管理员");
        }
    }

    @Override
    public R readMsg(Long msgId) {
        if (msgDao.readMsg(msgId) == 1) {
            return R.ok("read message successfully");
        } else {
            return R.error("已读信息错误...");
        }
    }

    @Override
    public R delMsg(Long msgId) {
        if (msgDao.deleteMsg(msgId) == 1) {
            return R.ok("delete message successfully");
        } else {
            return R.error("删除消息记录错误...");
        }
    }

    @Override
    public R getUnread(Long recipientId) {
        List<MsgRes> list = msgDao.getUnreadList(recipientId);
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        data.put("total", list.size());
        return R.ok(data, "success");
    }

    @Override
    public R searchContacts(String name) {
        Map<String, Object> data = new HashMap<>();
        data.put("admin", adminDao.getContacts(name));
        data.put("student", studentDao.getContacts(name));
        return R.ok(data, "success");
    }
}
